package com.industry.system.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.industry.framework.common.constant.Global;
import com.industry.framework.common.redis.RedisUtils;
import com.industry.framework.core.annountions.monitor.IdooMonitorService;
import com.industry.framework.core.generic.AbstractCoreGenericService;
import com.industry.system.controller.vo.MenuTreeRespVO;
import com.industry.system.dal.dataobject.SystemMenu;
import com.industry.system.dal.db.SystemMenuMapper;
import com.industry.system.dal.redis.MenuKeyConstants;
import com.industry.system.utils.SystemMenuUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SystemMenuService extends AbstractCoreGenericService<SystemMenu, String> {
    @Resource
    private SystemMenuMapper mapper;

    @CacheEvict(cacheNames = MenuKeyConstants.TREE_NAMES, key = "'all'") // for test.
    public List<SystemMenu> listRootMenus() {
        return mapper.selectList(
                Wrappers.lambdaQuery(SystemMenu.class)
                        .eq(SystemMenu::getStatus, 1)
                        .eq(SystemMenu::getParentId, 0L).orderByAsc(SystemMenu::getOrderNum)
        );
    }

    //获取所有可用模块 +  菜单
    public List<MenuTreeRespVO> listTreeMenus() {
        List<SystemMenu> menus = mapper.selectList(
                Wrappers.lambdaQuery(SystemMenu.class)
                        .eq(SystemMenu::getStatus, 0).orderByAsc(SystemMenu::getOrderNum)
        );

        MenuTreeRespVO root = new MenuTreeRespVO();
        root.setId("0");
        SystemMenuUtils.convertTree(menus, root);
        return root.getChildren();
    }

    //用户登录获取menu相关数据
    public List<SystemMenu> getUserMenuInfosByLogin() {
        String key = Global.authPermissionPrefix + ":" + StpUtil.getTokenInfo().getLoginId();
        List<String> cacheMenuIdsList = RedisUtils.getCacheObject(key);
        if (CollectionUtils.isEmpty(cacheMenuIdsList)) {
            return new ArrayList<>();
        }
        return mapper.selectList(Wrappers.lambdaQuery(SystemMenu.class)
                .in(SystemMenu::getId, cacheMenuIdsList).orderByAsc(SystemMenu::getOrderNum));
    }

    //菜单管理-获取所有模块数据
    public List<SystemMenu> getAllModules() {
        return mapper.selectList(
                Wrappers.lambdaQuery(SystemMenu.class)
                        .eq(SystemMenu::getParentId, 0L).orderByAsc(SystemMenu::getOrderNum)
        );
    }


    //菜单管理-根据Id获取菜单列表
    public List<MenuTreeRespVO> queryMenusByModuleId(String moduleId) {
        SystemMenu systemMenu = mapper.selectById(moduleId);
        if (systemMenu == null) {
            return new ArrayList<>();
        }
        //获取module下的菜单数据
        List<SystemMenu> systemMenus = mapper.selectList(
                Wrappers.lambdaQuery(SystemMenu.class)
                        .eq(SystemMenu::getModuleKey, systemMenu.getModuleKey()).orderByAsc(SystemMenu::getOrderNum)
        );
        MenuTreeRespVO root = new MenuTreeRespVO();
        root.setId(systemMenu.getId());
        SystemMenuUtils.convertTree(systemMenus, root);
        return root.getChildren();
    }


    //加载菜单详情
    public SystemMenu queryMenuById(String menuId) {
        return mapper.selectById(menuId);
    }

    //返回模块下 目录类型数据 或菜单类型数据
    public List<SystemMenu> queryMenuConfigSelect(String moduleKey, String type) {
        if (StringUtils.isAnyEmpty(moduleKey, type)) {
            return new ArrayList<>();
        }
        //获取module下的菜单数据
        List<SystemMenu> menus = mapper.selectList(
                Wrappers.lambdaQuery(SystemMenu.class)
                        .eq(SystemMenu::getModuleKey, moduleKey).orderByAsc(SystemMenu::getOrderNum)
        );
        if (CollectionUtils.isEmpty(menus)) {
            return new ArrayList<>();
        }
        if (StringUtils.equals("C", type)) {
            menus = menus.stream().filter(i -> StringUtils.equals("D", i.getMenuType()) || StringUtils.equals("M", i.getMenuType()))
                    .collect(Collectors.toList());
            menus.forEach(i -> {
                if (StringUtils.equals("M", i.getMenuType())) {
                    i.setMenuName("根目录");
                }
            });
        }
        if (StringUtils.equals("B", type)) {
            menus = menus.stream().filter(i -> StringUtils.equals("C", i.getMenuType())).collect(Collectors.toList());
        }
        return menus;
    }


    //新增菜单
    @IdooMonitorService("新增菜单")
    public boolean insert(SystemMenu systemMenu) {
        if (!StringUtils.isEmpty(systemMenu.getModuleKey()) && StringUtils.equals(systemMenu.getMenuType(), "D")) {
            //如果新增的是目录，根据moduleKey 查询对应模块
            List<SystemMenu> systemMenus = mapper.selectList(Wrappers.lambdaQuery(SystemMenu.class)
                    .eq(SystemMenu::getModuleKey, systemMenu.getModuleKey()).eq(SystemMenu::getMenuType, "M"));
            if (!CollectionUtils.isEmpty(systemMenus)) {
                SystemMenu module = systemMenus.get(0);
                systemMenu.setParentId(module.getId());
            }
        }
        return mapper.insert(systemMenu) > 0;
    }

    //修改菜单信息
    @IdooMonitorService("修改菜单")
    public void modify(SystemMenu systemMenu) {
        mapper.updateById(systemMenu);
    }

}
